package com.cdsxt.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

public class FreeMarkerUtil2 {

	
	public static void main(String[] args) {
		//设置模版的数据
		Map<String, Object> paramData=new HashMap<String, Object>();
		paramData.put("curusername", "张无忌！！！");
		paramData.put("sso_addr", "http:sso.com");
		paramData.put("sso_front_register_page_path", "/sso/1111");
		
		
		//进行Freemarker解析得到html字符串
		String htmlString = getOutString(paramData, "com/cdsxt/common/util/userFunction.ftl");
		System.out.println(htmlString);
	}
	
	
	//环境对象
	private static Configuration configuration;
	
	/**
	 * 加载环境-只需要一次
	 * @param freeMarkerPageDir
	 */
	static {
		try {
			// 创建一个合适的Configration对象
			configuration = new Configuration();
			// FreeMarker模版的文件夹
			//"D:\\\\software\\\\eclipse_javaEE\\\\workspace_gaoji1\\\\test_ssm_freemarker\\\\WebContent\\\\freemarkerPage";
			configuration.setObjectWrapper(new DefaultObjectWrapper());// 类型映射
			configuration.setDefaultEncoding("UTF-8"); // 这个一定要设置，不然在生成的页面中 会乱码
			//防止取出数据为空的问题
			configuration.setClassicCompatible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * @param writer
	 * @param paramData
	 * @param  freeMarkerFilePath classpath的Freemarker文件路径
	 */
	public static void writeOutStringToWriter(Writer writer,Object paramData,String freeMarkerFilePath){
		Template template = FreeMarkerUtil2.getTemplate(freeMarkerFilePath);
        try {
        	 
			template.process(paramData, writer);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 
	 * @param writer
	 * @param paramData
	 * @param  freeMarkerFilePath classpath的Freemarker文件路径
	 */
	public static String getOutString(Object paramData,String freeMarkerFilePath){
			
			try {
				//构建一个输出流：数据源（内存的ByteArray）
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				Writer writer= new OutputStreamWriter(baos, "utf-8");
				//把解析后的数据放入到输出流
				writeOutStringToWriter(writer, paramData, freeMarkerFilePath);
				//从内存的ByteArray取出数据
				String htmlStr= new String(baos.toByteArray(),"utf-8");
				//返回网页内容
				return htmlStr;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				return null;
			}
			
			
	}

	/**
	 * 获取classpath下的Freemarker模块文件的template的对象
	 * @param freeMarkerFilePath classpath的Freemarker文件路径
	 * @return 模块对象
	 */
	public static Template getTemplate(String freeMarkerFilePath) {
		try {
			//"com/cdsxt/sso/client/userFunction.ftl"
			InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(freeMarkerFilePath);
			// 获取或创建一个模版-模版的文件夹
			Reader reader=new InputStreamReader(is, "utf-8");
			Template template = new Template("temp"+Math.random(), reader, configuration);
			return template;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
